<template>
  <pre>{{ dump }}</pre>
</template>

<script setup>
/*
* 用vue3，开发一个红绿灯路口的模拟程序， 有四红绿灯，四条车道，标出车道的序号和方向，每个车道有随机10辆车以内数量的车子经过，经过红绿灯时如果红灯停，绿灯则正常通行，每个红绿灯30s的倒计时，中间3s的黄灯切换到下一个红灯，黄灯车子也要停 给出具体代码, 用纯数字模拟，给出涉及对象和属性的值，每秒钟要刷新
* */

/* ========= 1. 常量 ========= */
const DUR = { green: 30, yellow: 3, red: 33 }; // 红灯=绿+黄

/* ========= 2. 响应式状态 ========= */
import { reactive, computed, onMounted, onUnmounted } from 'vue';

// 2-1 四个信号灯
// 属性：color, count(倒计时)
const lights = reactive([
  { id: 0, name: '北向', color: 'green', count: DUR.green }, 
  { id: 1, name: '东向', color: 'red',   count: DUR.red   },
  { id: 2, name: '南向', color: 'red',   count: DUR.red   },
  { id: 3, name: '西向', color: 'red',   count: DUR.red   }
]);

// 2-2 四条车道
// 属性：cars[] 每辆车 {id, pos}，pos 为 0-100 的整数（0=最远离路口，100=穿过路口）
const lanes = reactive([
  { id: 0, dir: '北→南', cars: [] },
  { id: 1, dir: '东→西', cars: [] },
  { id: 2, dir: '南→北', cars: [] },
  { id: 3, dir: '西→东', cars: [] }
]);

/* ========= 3. 初始化车辆 ========= */
function genCars () {
  lanes.forEach(lane => {
    const n = Math.floor(Math.random() * 11); // 0-10 辆
    lane.cars = Array.from({ length: n }, (_, i) => ({
      id: lane.id * 100 + i,
      pos: -20 - i * 10 // 负数表示离路口还远
    }));
  });
}
genCars();

/* ========= 4. 灯循环 ========= */
function stepLights () {
  // 找出当前绿灯索引
  const gIdx = lights.findIndex(l => l.color === 'green');

  // 所有灯倒计时 -1
  lights.forEach(l => l.count--);

  // 绿灯结束 -> 黄灯
  if (gIdx >= 0 && lights[gIdx].count === 0) {
    lights[gIdx].color = 'yellow';
    lights[gIdx].count = DUR.yellow;
    return;
  }

  // 黄灯结束 -> 红灯，并点亮下一绿灯
  const yIdx = lights.findIndex(l => l.color === 'yellow');
  if (yIdx >= 0 && lights[yIdx].count === 0) {
    lights[yIdx].color = 'red';
    lights[yIdx].count = DUR.red;

    const nextIdx = (yIdx + 1) % 4;
    lights[nextIdx].color = 'green';
    lights[nextIdx].count = DUR.green;
  }
}

/* ========= 5. 车辆移动 ========= */
function moveCars () {
  lanes.forEach((lane, idx) => {
    const light = lights[idx];
    lane.cars.forEach(car => {
      // 速度：1 格/秒
      let speed = 1;

      // 红灯或黄灯，且即将到达路口 -> 停在 0
      if ((light.color === 'red' || light.color === 'yellow') && car.pos + speed >= 0 && car.pos < 0) {
        car.pos = 0;
      }
      // 绿灯 或 已穿过路口 -> 正常前进
      else {
        car.pos += speed;
      }
    });

    // 移除已离开视野的车（>120）
    lane.cars = lane.cars.filter(c => c.pos <= 120);
  });
}

/* ========= 6. 定时刷新 ========= */
let timer = null;
onMounted(() => {
  timer = setInterval(() => {
    stepLights();
    moveCars();
  }, 1000);
});
onUnmounted(() => clearInterval(timer));

/* ========= 7. 纯文本展示 ========= */
const dump = computed(() => {
  let str = '=== 信号灯 ===\n';
  lights.forEach(l => {
    str += `${l.name.padEnd(4)} ${l.color.padEnd(5)} ${l.count}s\n`;
  });
  str += '\n=== 车道 ===\n';
  lanes.forEach(l => {
    str += `${l.dir.padEnd(6)} [${l.cars.map(c => c.pos).join(',') || '-'}]\n`;
  });
  return str;
});
</script>

<style>
pre {
  font-family: monospace;
  font-size: 14px;
  line-height: 1.4;
}
</style>